﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web;
using System.Web.Security;
using XQ.WeChatOfficialAccount.WebAPI.Filter;
using XQ.WeChatOfficialAccount.BLL.Account;
using XQ.WeChatOfficialAccount.DAL;
using XQ.WeChatOfficialAccount.DAL.Model.Sys;
using XQ.WeChatOfficialAccount.WebAPI.Models;
using System.Web.Http.Cors;
using XQ.WeChatOfficialAccount.WebAPI.Common;
using XQ.WeChatOfficialAccount.WebAPI.Common.WorkContext;
using System.Configuration;
using XQ.WeChatOfficialAccount.DAL.DAL.Common;
using XQ.WeChatOfficialAccount.DAL.DAL;
using XQ.WeChatOfficialAccount.DAL.Models;
using Newtonsoft.Json;
using XQ.WeChatOfficialAccount.BLL.Sys;
using XQ.WeChatOfficialAccount.DAL.Model.Business;
using XQ.WeChatOfficialAccount.BLL.Common;

namespace XQ.WeChatOfficialAccount.WebAPI.Controllers
{
    /// <summary>
    /// 账号相关
    /// </summary>
    public class AccountController : ApiController
    {
        UserDal userDal = new UserDal();
        private readonly WebWorkContext X = null;

        public AccountController()
        {
            this.X = new WebWorkContext(HttpContext.Current);
        }
        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="loginModel">用户名 密码</param>
        /// <returns></returns>
        [Route("Api/Account/Login")]
        public ResultModel Login(LoginModel loginModel)
        {
            ResultModel resultModel = new ResultModel();
            UserInfoResult userInfoResult = new UserInfoResult();
            try
            {
                Sys_Users user = LoginBll.Instance.GetLoginResult(loginModel.UserName, loginModel.Password);
                if (user != null)
                {
                    LogBll.Instance.WriteLog(LogBll.LogType.LogIn, "", user.id, "用户登录", "", "", "", user.TrueName);
                    resultModel.success = true;
                    
                    //账号禁用
                    if (user.IsDisabled == true)
                    {
                        resultModel.code = "10001";
                        resultModel.message = "帐号已被禁用！";
                        return resultModel;
                    }
                    this.X.SetUserLogin(user, false);
                    userInfoResult.User = user;
                    userInfoResult.RoleID = new RoleBll().GetRoleIDByUserID(user.id);
                    userInfoResult.Token = TokenHelper.CreateToken(user.id, user.DepartmentID, userInfoResult.RoleID);

                    resultModel.code = "10000";
                    resultModel.message = "调用成功";
                    resultModel.data = userInfoResult;
                    return resultModel;
                }
                else
                {
                    resultModel.code = "10002";
                    resultModel.message = "登录失败，无效的用户名或密码";
                    return resultModel;
                }
            }
            catch (Exception ex)
            {
                resultModel.success = false;
                resultModel.code = "10001";
                resultModel.message = "执行失败";
                resultModel.data = ex.Message;

                return resultModel;
            }

        }

        /// <summary>
        /// 监管绑定账号
        /// </summary>
        /// <param name="loginModel"></param>
        /// <returns></returns>
        [Route("Api/Account/BindOpenid")]
        public ResultModel BindOpenid(LoginModel loginModel)
        {
            ResultModel resultModel = new ResultModel();
            UserInfoResult userInfoResult = new UserInfoResult();
            try
            {
                Sys_Users user = LoginBll.Instance.GetLoginResult(loginModel.UserName, loginModel.Password);
                if (user != null)
                {
                    LogBll.Instance.WriteLog(LogBll.LogType.LogIn, "", user.id, "绑定账号对应的openid，验证登录", "", "", "", user.TrueName);

                    //暂没有验证此账号是否绑定过微信openid,有新绑定时直接替换原来的绑定
                    user.openid = loginModel.Openid;
                    userDal.UpdateModel(user);


                    resultModel.success = true;

                    //账号禁用
                    if (user.IsDisabled == true)
                    {
                        resultModel.code = "10001";
                        resultModel.message = "帐号已被禁用！";
                        return resultModel;
                    }
                    userInfoResult.User = user;
                    userInfoResult.RoleID = new RoleBll().GetRoleIDByUserID(user.id);
                    userInfoResult.Token = TokenHelper.CreateToken(user.id, user.DepartmentID, userInfoResult.RoleID);

                    resultModel.code = "10000";
                    resultModel.message = "调用成功";
                    resultModel.data = userInfoResult;
                    return resultModel;
                }
                else
                {
                    resultModel.success = false;
                    resultModel.code = "10002";
                    resultModel.message = "绑定失败，无效的用户名或密码";
                    return resultModel;
                }
            }
            catch (Exception ex)
            {
                resultModel.success = false;
                resultModel.code = "10001";
                resultModel.message = "执行失败";
                resultModel.data = ex.Message;

                return resultModel;
            }
        }

        /// <summary>
        /// 监管解绑账号对应的openid
        /// </summary>
        /// <returns></returns>
        [Route("Api/Account/UnBindOpenid")]
        public ResultModel UnBindOpenid()
        {
            ResultModel resultModel = new ResultModel();
            
            try
            {
                TokenModel token = TokenHelper.GetTokenByHeaders(Request.Headers);
                LogBll.Instance.WriteLog(LogBll.LogType.Other, "", token.UID, "监管解绑账号对应的openid", "", "", "", "Api/Account/UnBindOpenid:"+JsonConvert.SerializeObject(token));
                if (token != null && token.UID > 0)
                {
                    Sys_Users user = userDal.FindModel(u => u.id == token.UID);
                    user.openid = "";
                    resultModel.data = userDal.UpdateModel(user) == 1;
                    resultModel.success = true;
                    resultModel.code = "10000";
                    resultModel.message = "调用成功";

                }
                else {
                    resultModel.success = false;
                    resultModel.code = "10001";
                    resultModel.message = "Token解析失败！";
                }
                return resultModel;
            }
            catch (Exception ex)
            {
                LogBll.Instance.WriteErrLog("", 0, "监管解绑账号对应的openid", "", "", "", ex.Message, "", "AccountController", "UnBindOpenid");
                resultModel.success = false;
                resultModel.code = "10001";
                resultModel.message = "执行失败";
                resultModel.data = ex.Message;

                return resultModel;
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("Api/Account/UpdatePassword")]
        public ResultModel UpdatePassword([FromBody] UpdatePasswordModel model)
        {
            ResultModel resultModel = new ResultModel();
            resultModel.success = false;
            resultModel.code = "10001";
            resultModel.message = "执行失败";
            resultModel.data = "原密码不正确";

            TokenModel token = TokenHelper.GetTokenByHeaders(Request.Headers);
            try
            {
                if(token ==null || token.UID==0)
                {
                    resultModel.data = "没有获取到Token信息";
                    return resultModel;
                }
                model.UserID = token.UID;
                Sys_Users user = LoginBll.Instance.GetUserByIDAndPassword(model.UserID, model.OldPassword);
                if (user != null)
                {
                    UserBLL bll = new UserBLL();
                    user.Password = model.NewPassword;                    
                    resultModel.data = bll.SaveUser(user) == 1;
                    resultModel.success = true;
                    resultModel.code = "10000";
                    resultModel.message = "执行成功";
                }
                LogBll.Instance.WriteLog(LogBll.LogType.Other, "", 0, "修改密码", "", "", "", "Api/Account/UpdatePassword：" + JsonConvert.SerializeObject(model) + JsonConvert.SerializeObject(token));
                return resultModel;
            }
            catch (Exception ex)
            {
                LogBll.Instance.WriteErrLog("", 0, "修改密码报错", "", "", JsonConvert.SerializeObject(model) + JsonConvert.SerializeObject(token), ex.Message, "", "AccountController", "UpdatePassword");
                resultModel.success = false;
                resultModel.code = "10001";
                resultModel.message = "执行失败";
                resultModel.data = ex.Message;

                return resultModel;
            }
        }
    }
}